package com.example.zzj.ziwuyundemo.activity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zzj.ziwuyundemo.MainActivity;
import com.example.zzj.ziwuyundemo.R;
import com.example.zzj.ziwuyundemo.adapter.MainAdapter;
import com.example.zzj.ziwuyundemo.base.BaseActivity;
import com.example.zzj.ziwuyundemo.entity.LoginEntity;
import com.example.zzj.ziwuyundemo.fragment.MessageFragment;
import com.example.zzj.ziwuyundemo.util.NotWork;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.params.HttpConnectionParams;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zzj on 2016/12/1.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    @InjectView(R.id.name)
    EditText name;
    @InjectView(R.id.password)
    EditText password;
    @InjectView(R.id.login)
    Button login;
    @InjectView(R.id.checkbox)
    CheckBox checkbox;
    @InjectView(R.id.tv_forgetPW)
    TextView tvForgetPW;
    private LoginEntity loginEntity;

    private boolean mobileLogin = true;
    static String YES = "yes";
    static String NO = "no";
    static String user, pwd;
    private String isMemory = "";//isMemory变量用来判断SharedPreferences有没有数据，包括上面的YES和NO
    private String FILE = "saveUserNamePwd";//用于保存SharedPreferences的文件
    private SharedPreferences sp = null;//声明一个SharedPreferences
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private boolean isNetworkAvailable;
    private static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟    
    private static final int SO_TIMEOUT = 10*1000;//设置等待数据超时时间10秒钟 

    OkHttpClient okHttpClient;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);

        sp = getSharedPreferences(FILE, MODE_PRIVATE);
        isMemory = sp.getString("isMemory", NO);
        //进入界面时，这个if用来判断SharedPreferences里面name和password有没有数据，有的话则直接打在EditText上面
        if (isMemory.equals(YES)) {
            user = sp.getString("name", "");
            pwd = sp.getString("password", "");
            name.setText(user);
            password.setText(pwd);
        }
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(user, name.toString());
        editor.putString(pwd, password.toString());
        editor.commit();

        initView();
        initDate();
    }

    private void initDate() {
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (checkbox.isChecked()) {
                    sp.edit().putBoolean("ISCHECK", true).commit();
                } else {
                    sp.edit().putBoolean("ISCHECK", false).commit();
                }
            }
        });
    }

    private void initView() {
        setOnClick();
        checkbox.setChecked(true);
    }

    private void setOnClick() {
        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                user = name.getText().toString();
                pwd = password.getText().toString();
                remenber();
                if (TextUtils.isEmpty(name.getText()) || TextUtils.isEmpty(password.getText())) {
                    Toast.makeText(mContext, getString(R.string.text_verify_login), Toast.LENGTH_SHORT).show();
                } else {
                    NotWork.isNetworkAvailable(mContext);
                    okHttpClient = new OkHttpClient();
                    FormEncodingBuilder builder = new FormEncodingBuilder();
                    builder.add("username", user);
                    builder.add("password", pwd);
                    builder.add("mobileLogin", String.valueOf(mobileLogin));

                    //超时
                    okHttpClient.setConnectTimeout(10,TimeUnit.SECONDS);
                    okHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
                    okHttpClient.setWriteTimeout(10,TimeUnit.SECONDS);

                    final Request request = new Request.Builder()
                            .url("http://192.168.1.75:8080/mclcm/a/mclcm/test/login")
                            .post(builder.build())
                            .build();
                    Log.d("request", request.toString());
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Request request, IOException e) {

                        }

                        @Override
                        public void onResponse(Response response) throws IOException {
                            final String res = response.body().string();
                                Log.d("sssss", res);
                            if (res.equals("")){
                                Toast.makeText(mContext, getString(R.string.text_error_login), Toast.LENGTH_SHORT).show();
                            }else{
                                Gson gson = new Gson();
                                loginEntity = new LoginEntity();
                                loginEntity = gson.fromJson(res, LoginEntity.class);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String success = loginEntity.getIsLogin();
                                        if (success.equals("success")) {
                                            Toast.makeText(mContext, "成功了", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(mContext, MainActivity.class);//跳转
                                            intent.putExtra("photo", loginEntity.getPhoto());
                                            intent.putExtra("userN", loginEntity.getUser().getName());
                                            intent.putExtra("id",loginEntity.getUser().getId());
                                            startActivity(intent);
                                            finish();

                                        } else {
                                            Toast.makeText(mContext, getString(R.string.text_error_login), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }

                        }
                    });

                }
                break;
        }
    }

    // remenber方法用于判断是否记住密码，checkBox1选中时，提取出EditText里面的内容，放到SharedPreferences里面的name和password中
    public void remenber() {
        if (checkbox.isChecked()) {
            if (sp == null) {
                sp = getSharedPreferences(FILE, MODE_PRIVATE);
            }
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("name", name.getText().toString());
            edit.putString("password", password.getText().toString());
            edit.putString("isMemory", YES);
            edit.commit();
        } else if (!checkbox.isChecked()) {
            if (sp == null) {
                sp = getSharedPreferences(FILE, MODE_PRIVATE);
            }
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("isMemory", NO);
            edit.commit();
        }
    }
}

